package com.cskaoyan.service.wx.footprint;

import com.cskaoyan.dao.footprint.FootPrintDao;
import com.cskaoyan.model.realm.WxLoginUserData;
import com.cskaoyan.model.wx.footprint.vo.FootPrintListDataVo;
import com.cskaoyan.model.wx.footprint.vo.FootPrintListVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class FootPrintServiceImpl implements FootPrintService {


    @Autowired
    FootPrintDao dao;

    @Override
    @Transactional
    public FootPrintListVo getFootPrintList(Integer page, Integer limit) {

        if (page == null || limit == null) {
            return null;
        }
        WxLoginUserData subject = (WxLoginUserData) SecurityUtils.getSubject().getPrincipal();


        PageHelper.startPage(page, limit);
        List<FootPrintListDataVo> list = dao.getGoodsInfo(subject.getId());
        PageInfo<FootPrintListDataVo> info = new PageInfo<>(list);

        // 转换结果集
        FootPrintListVo result = new FootPrintListVo();
        result.setList(list);
        result.setPages(info.getPages());
        result.setTotal((int) info.getTotal());
        result.setPage(page);
        result.setLimit(limit);

        return result;
    }

    /***
     *  历史足迹该事务的运行不会影响外围事务的正常实行。
     *
     */
    @Transactional(propagation = Propagation.NESTED)
    @Override
    public void addFootPrint(Integer userId, Integer goodsId) {
        if (userId == null || goodsId == null) {
            return;
        }
        int affectRows = dao.updateFootPrintInfo(userId, goodsId);
        if (affectRows == 0) {
            dao.addNewFootPrintInfo(userId, goodsId);
        }
    }

    @Override
    public void deleteFootPrint(Integer footId) {
        dao.deleteFootPrint(footId);
    }


}
